<?php
namespace application\index\model;

class ApiFront
{
	public $code;
	public $message;

	/**
	 * 接收内容推送
	 */
	public function newsPost()
	{
		$token	 = input('token', '');
		$content = input('data', '');
		//验证token
		if(!authcode($token)) {
			$this->code = '1500';
			$this->message = 'token验证失败';
			return false;
		}
		//验证内容
		$content = json_decode($content, true);
		if(!$content) {
			$this->code = '1500';
			$this->message = '内容为空';
			return false;
		}
		//文章分类列表
		$list  = $this->getArticleCat();
		$catid = [];
		foreach($list as $value) {
			$catid[] = $value['catid'];
		}
		//解析保存内容
		$article = new \application\common\model\Article();
		$count   = 0;
		$pushUrl = [];	//推送链接数组http://emotion.aibaiwan.cn/detail/1965
		foreach($content as $key => $val) {
			if(!isset($val['title']) || !isset($val['catid']) || !in_array($val['catid'], $catid) || empty($val['content'])) continue;
			if(isset($val['aid'])) unset($content[$key]['aid']);
			$aid = $article->saveArticle($val);
			if($aid) {
				$pushUrl[] = 'http://'.$_SERVER['HTTP_HOST'].'/detail/'.$aid;
				$count++;
			}
		}
		//seo收录相关
		if($pushUrl) {
			//百度推送
			//$this->pushBaidu($pushUrl);
			//更新sitemap
			$this->refreshSitemap($pushUrl);
		}
		//返回显示结果
		return sprintf('count:%d', $count);
	}
	/**
	 * 获取文章分类列表
	 */
	public function getArticleCat()
	{
		$cat  = \application\common\model\ArticleCat::All();
        $list = collection($cat)->toArray();
        return $list;
	}	
	/**
	 * 推送至百度链接
	 * @param array $urlArr 推送链接数组
	 */
	private function pushBaidu($urlArr)
	{
		if(!$urlArr) return false;
		$api = sprintf('http://data.zz.baidu.com/urls?site=%s&token=%s', $_SERVER['HTTP_HOST'], config('baidu_push_token'));
		$ch  = curl_init();
		$options =  array(
		    CURLOPT_URL  => $api,
		    CURLOPT_POST => true,
		    CURLOPT_RETURNTRANSFER => true,
		    CURLOPT_POSTFIELDS => implode("\n", $urlArr),
		    CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
		);
		curl_setopt_array($ch, $options);
		curl_exec($ch);
	}
	/**
	 * 更新sitemap文件
	 * @param array $urlArr 推送链接数组
	 */
	private function refreshSitemap($urlArr)
	{
		$file = $_SERVER['DOCUMENT_ROOT'].'/sitemap.txt';
		$data = implode("\n", $urlArr);
		if (is_file($file)) {
			$filesize = abs( filesize($file) );
			//文件大于1m重新生成文件，原来内容删除
			if($filesize > 1024000) {
				file_put_contents($file, $data);
			} else {
				$data = "\n" . $data;
				file_put_contents($file, $data, FILE_APPEND);
			}
		} else {
			file_put_contents($file, $data);
		}
	}
}